package com.timothy.android;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class CommonTest {
	private static String HEADER = "<Header>" +
		"<Phone IPAddress=\""+getIp()+"\" Name=\"\" Port=\""+9999+"\"></Phone>" +
	"</Header>";
	
	public static void main(String[] args) {
		HEADER = HEADER.replaceAll("Name=\"[^\"]*\"", "Name=\""+"testtest"+"\"");
		
		System.out.println(HEADER);
	}
	
	private static String getIp(){
        String localip=null;//本地IP，如果没有配置外网IP则返回它
        String netip=null;  //外网IP
        try {
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while( netInterfaces.hasMoreElements() ) {
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while( address.hasMoreElements() ) {
                    InetAddress ip=address.nextElement();
                    if( ip.isLoopbackAddress() || ip.getHostAddress().indexOf(":")!=-1 )
                        continue;
                    
                    if( ip.isSiteLocalAddress() ){ //内网IP
                        localip=ip.getHostAddress();
                    } else { //外网IP     
                        netip = ip.getHostAddress();
                        break;
                    }
                }
                
                if( netip!=null )
                    break;
            }
        } catch (SocketException e) {
        }
        
        if(  netip!=null  )
            return netip;
        else if ( localip!=null )
            return localip;
        else
            return "127.0.0.1";
    } 
}
